<?php
class ModelSaleCustomerGrade extends Model {
	public function addCustomerGrade($data) {
		$customer_grade_id = $this->db->insert('customer_grade', $data);

		foreach ($data['customer_grade_description'] as $language_id => $value) {
			$value['language_id'] = $language_id;
			$value['customer_grade_id'] = $customer_grade_id;
			$this->db->insert('customer_grade_description', $value);
		}
	}

	public function editCustomerGrade($customer_grade_id, $data) {
		$this->db->update('customer_grade', $data, array('customer_grade_id' => $customer_grade_id));

		$this->db->query("DELETE FROM  @@customer_grade_description WHERE customer_grade_id = " . (int)$customer_grade_id);

		foreach ($data['customer_grade_description'] as $language_id => $value) {
			$value['language_id'] = $language_id;
			$value['customer_grade_id'] = $customer_grade_id;
			$this->db->insert('customer_grade_description', $value);
		}
	}

	public function deleteCustomerGrade($customer_grade_id) {
		$this->db->query("DELETE FROM  @@customer_grade WHERE customer_grade_id = " . (int)$customer_grade_id);
		$this->db->query("DELETE FROM  @@customer_grade_description WHERE customer_grade_id = " . (int)$customer_grade_id);
	}

	public function getCustomerGrade($customer_grade_id) {
		return $this->db->queryOne("SELECT DISTINCT * FROM  @@customer_grade cg LEFT JOIN  @@customer_grade_description cgd
				ON (cg.customer_grade_id = cgd.customer_grade_id) WHERE cg.customer_grade_id = " . (int)$customer_grade_id
				. " AND cgd.language_id = " . (int)C('config_language_id'));
	}

	public function getCustomerGrades($filter = null) {
		$sql = "SELECT * FROM  @@customer_grade cg LEFT JOIN  @@customer_grade_description cgd ON (cg.customer_grade_id = cgd.customer_grade_id)
				WHERE cgd.language_id = " . (int)C('config_language_id');

		if ($filter) {
			$sql .= $filter->sort('cg.sort_order');
			$sql .= $filter->limit();
				
		}
		else $sql .= " ORDER BY cg.sort_order";
			
		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getCustomerGradeDescriptions($customer_grade_id) {
		$customer_grade_data = array();

		$query = $this->db->query("SELECT * FROM  @@customer_grade_description WHERE customer_grade_id = " . (int)$customer_grade_id);

		foreach ($query->rows as $result) {
			$customer_grade_data[$result['language_id']] = array(
					'name'        => $result['name'],
					'description' => $result['description']
			);
		}

		return $customer_grade_data;
	}

	public function getTotalCustomerGrades() {
		return $this->db->queryOne("SELECT COUNT(*) AS total FROM  @@customer_grade");
	}
}